package com.cheney.mapboxexample.common;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

/**
 * @author CHENEY
 * @date 2022/3/26
 */
public class ViewUtil {

    public interface OnViewClickPosListener {
        /**
         * 一次单击事件触发
         * @param clickX    相对view左上角点击位置X
         * @param clickY    相对view左上角点击位置Y
         */
        void onClick(float clickX, float clickY);
    }

    /**
     * 分发view的单击事件
     */
    @SuppressLint("ClickableViewAccessibility")
    public static void setOnViewClickPosListener(Context context, View view, OnViewClickPosListener listener){
        if (view == null || listener == null) {
            return;
        }
        // 用于区分单双击
        GestureDetector mGestureDetector = new GestureDetector(context, new GestureDetector.OnGestureListener() {
            @Override
            public boolean onDown(MotionEvent e) {
                return false;
            }

            @Override
            public void onShowPress(MotionEvent e) {

            }

            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                return false;
            }

            @Override
            public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
                return false;
            }

            @Override
            public void onLongPress(MotionEvent e) {

            }

            @Override
            public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
                return false;
            }
        });
        mGestureDetector.setOnDoubleTapListener(new GestureDetector.OnDoubleTapListener() {
            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                listener.onClick(e.getX(), e.getY());
                return false;
            }

            @Override
            public boolean onDoubleTap(MotionEvent e) {
                return false;
            }

            @Override
            public boolean onDoubleTapEvent(MotionEvent e) {
                return false;
            }
        });
        view.setOnTouchListener((v, event) -> mGestureDetector.onTouchEvent(event));
    }

    /**
     * 设置view的大小
     */
    public static void layoutView(View v, int width, int height) {
        if (v == null || width <= 0 || height <=0) {
            return;
        }
        v.layout(0,0, width, height);
        int measuredWidth = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.AT_MOST);
        int measuredHeight = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.AT_MOST);
        v.measure(measuredWidth, measuredHeight);
        v.layout(0,0, v.getMeasuredWidth(), v.getMeasuredHeight());
    }
}
